package com.jml.整合springboot.service;

import com.alibaba.fastjson.JSONObject;
import java.util.UUID;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.MessagePostProcessor;

import java.awt.font.ShapeGraphicAttribute;

@Component
public class FanoutProducer {
	@Autowired
	private AmqpTemplate amqpTemplate;
	
	@Autowired
	private RabbitTemplate rabbitTemplate;

	public void send(String queueName) {
		String msg = "my_fanout_msg:" + queueName;
		System.out.println("发送信息" + ":" + msg);
		//这种没用到路由，是点对点，只有队列
		//队列名字，消息内容
		amqpTemplate.convertAndSend(queueName, msg);
		
		//根据交换机路由键订阅，用到交换机和路由键
		//amqpTemplate.convertAndSend("topic.t.o",msg);
		//交换机 ，路由键，消息内容
		amqpTemplate.convertAndSend("topicExchange","topic.t.o",msg);
	}
	
	//消息设置全局消息ID
	public void sendDead(String queueName) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("email", "644064779");
		jsonObject.put("timestamp", 0);

		String jsonString = jsonObject.toJSONString();
		System.out.println("jsonString:" + jsonString);
		// 生产者发送消息的时候需要设置消息id
		Message message = MessageBuilder.withBody(jsonString.getBytes())
				.setContentType(MessageProperties.CONTENT_TYPE_JSON).setContentEncoding("utf-8")
				.setMessageId(UUID.randomUUID() + "").build();

		amqpTemplate.convertAndSend(queueName, message);
	}
	
	@Async
	public void sendMsg(String msg) {
		rabbitTemplate.convertAndSend("orderExchange", "orderRoutingKey", msg,
				new MessagePostProcessor() {
					@Override
					public Message postProcessMessage(Message message) throws AmqpException {
						//设置过期时间
						message.getMessageProperties().setExpiration("10000");
						return message;
					}
				});
		// 消息投递失败
	}
}

